package com.tubemostwanted.model;

import java.util.List;

import com.tubemostwanted.entity.Tag;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class TagModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();

	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	public static boolean add(Tag tag) {
		try {
			initPm();
			pm.makePersistent(tag);

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Tag> listTag) {
		try {
			initPm();
			pm.makePersistentAll(listTag);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Tag tag) {
		initPm();
		pm.makePersistent(tag);
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Tag getByAlias(String alias) {
		initPm();
		Tag tag = null;
		Query query = pm.newQuery(Tag.class);
		query.setFilter("alias==tagAlias");
		query.declareParameters("java.lang.String tagAlias");
		query.setRange(0, 1);
		List<Tag> listResult = (List<Tag>) query.execute(alias);
		if (listResult.size() > 0) {
			tag = listResult.get(0);
		}
		return tag;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Tag> getTop10View() {
		initPm();
		Query query = pm.newQuery(Tag.class);		
		query.setOrdering("count desc");
		query.setRange(0, 10);
		List<Tag> listResult = (List<Tag>) query.execute();
		return listResult;
	}

	public static void closePM() {
		pm.close();
	}

}
